#!/usr/bin/env python3
"""
项目安装脚本
自动创建虚拟环境并安装依赖
"""

import os
import sys
import subprocess
import platform

def run_command(command, shell=False):
    """执行命令"""
    try:
        result = subprocess.run(command, shell=shell, check=True, capture_output=True, text=True)
        print(f"✅ 执行成功: {' '.join(command) if isinstance(command, list) else command}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 执行失败: {' '.join(command) if isinstance(command, list) else command}")
        print(f"错误信息: {e.stderr}")
        return False

def main():
    print("🚀 开始安装 lecture-text2sql 项目...")
    
    # 检查Python版本
    python_version = sys.version_info
    if python_version < (3, 8):
        print(f"❌ Python版本过低: {python_version.major}.{python_version.minor}")
        print("请升级到Python 3.8或更高版本")
        return False
    
    print(f"✅ Python版本: {python_version.major}.{python_version.minor}.{python_version.micro}")
    
    # 检查是否已存在虚拟环境
    venv_path = "venv"
    if os.path.exists(venv_path):
        print("⚠️ 虚拟环境已存在，跳过创建")
    else:
        print("📦 创建虚拟环境...")
        if not run_command([sys.executable, "-m", "venv", venv_path]):
            return False
    
    # 确定激活脚本路径
    if platform.system() == "Windows":
        activate_script = os.path.join(venv_path, "Scripts", "activate")
        pip_path = os.path.join(venv_path, "Scripts", "pip")
    else:
        activate_script = os.path.join(venv_path, "bin", "activate")
        pip_path = os.path.join(venv_path, "bin", "pip")
    
    # 升级pip
    print("🔧 升级pip...")
    if not run_command([pip_path, "install", "--upgrade", "pip"]):
        print("⚠️ pip升级失败，继续安装依赖")
    
    # 安装依赖
    print("📚 安装项目依赖...")
    if not run_command([pip_path, "install", "-r", "requirements.txt"]):
        return False
    
    print("\n" + "="*50)
    print("🎉 安装完成！")
    print("="*50)
    print("\n📋 下一步操作:")
    print("1. 激活虚拟环境:")
    if platform.system() == "Windows":
        print("   venv\\Scripts\\activate")
    else:
        print("   source venv/bin/activate")
    print("\n2. 配置数据库连接:")
    print("   编辑 config/mysql_config.py")
    print("\n3. 设置API密钥:")
    print("   export OPENAI_API_KEY='your-api-key'")
    print("\n4. 运行项目:")
    print("   python main.py")
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)